import {
    StyleSheet,
    Text,
    View,
    Image,
    ImageBackground,
    ScrollView,
    TextInput,
    TouchableOpacity,
    Pressable,
} from 'react-native';
import React, { useState } from 'react';
import Icon from 'react-native-vector-icons/Ionicons';
import { useTranslation } from 'react-i18next';
import { FocusAwareStatusBar } from '~/components';
import { px2dp, scale } from '~/utils/px2dp';
import { isEmailValid } from '~/utils/rules';
import { useNavigation } from '@react-navigation/native';
import { emailLoginApi, getUserInfo } from '~/api/loginApi';
import { userStore } from '~/store';

export default function LoginByEmail() {
    const { t } = useTranslation();
    const navigation = useNavigation<any>();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    // 获取验证码
    const Login = () => {
        if (!email && !password) {
            Toast.show({ content: t('LoginByEmail.t1'), layout: 'top' });
            return;
        }
        // if (!isEmailValid(email)) {
        //     Toast.show({ content: t('LoginByEmail.t2'), layout: 'top' });
        //     return;
        // }
        emailLoginApi({ email, password }).then((res) => {
            if (res.status == 1) {
                const { token, user_id } = res;
                setTimeout(() => {
                    getInfo(token);
                }, 200);
            } else {
                if (res.msg == '账号或密码错误 ') {
                    Toast.show({ content: t('LoginByEmail.t3'), layout: 'top' });
                } else {
                    Toast.show({ content: t('LoginByEmail.t4'), layout: 'top' });
                }
            }
        });
    };
    const getInfo = (token) => {
        getUserInfo(token).then((res) => {
            if (res.status !== 1) {
                Toast.show({ content: t('LoginByEmail.t4'), layout: 'top' });
                return;
            }
            const {
                avatar,
                armarium_science_user_birthday,
                armarium_science_user_id,
                armarium_science_user_name,
                armarium_science_user_sex,
                armarium_science_user_sg,
                armarium_science_user_tz,
                blood_pressure,
                circle_id,
                has_yjh,
                heart_rate,
                is_yjh_user,
                user_type,
            } = res.data.user_info;
            // const phone = email.replace(/\D/g, '');
            let obj = {
                avatar,
                user_id: armarium_science_user_id,
                email: email,
                armarium_science_user_birthday,
                armarium_science_user_name,
                armarium_science_user_sex,
                armarium_science_user_sg,
                armarium_science_user_tz,
                blood_pressure,
                circle_id,
                has_yjh,
                heart_rate,
                is_yjh_user,
                token,
                user_type,
            };
            userStore.signIn(obj);
            navigation.navigate('Main');
        });
    };
    return (
        <View style={styles.container}>
            <FocusAwareStatusBar translucent={true} />
            <ImageBackground style={styles.bg} source={require('~/assets/login/bg4.png')}>
                <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.contentContainerStyle}>
                    <TouchableOpacity style={styles.close} onPress={() => navigation.goBack()}>
                        <Icon name={'chevron-back-outline'} size={px2dp(60)} color={'#fff'}></Icon>
                    </TouchableOpacity>
                    <View style={styles.content}>
                        <Image
                            resizeMode="contain"
                            style={styles.logoImage}
                            source={{
                                uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/10/eecd820251009135831105.png',
                            }}
                        />
                        <View>
                            <Text style={styles.title}>{t('LoginByEmail.t12')}</Text>
                            <Text style={styles.tips}>{t('LoginByEmail.t13')}</Text>
                        </View>
                        <View style={styles.inputContent}>
                            <Text style={styles.tips}>{t('LoginByEmail.t5')}</Text>
                            <View style={[styles.input]}>
                                <TextInput
                                    style={styles.inputStyle}
                                    placeholder={t('LoginByEmail.t6')}
                                    returnKeyType={'done'}
                                    value={email}
                                    onChangeText={(val) => {
                                        setEmail(val);
                                    }}
                                    placeholderTextColor={'#a4a4a4'}
                                />
                            </View>
                        </View>
                        <View style={styles.inputContent}>
                            <Text style={styles.tips}>{t('LoginByEmail.t8')}</Text>
                            <View style={[styles.input]}>
                                <TextInput
                                    style={styles.inputStyle}
                                    placeholder={t('LoginByEmail.t7')}
                                    returnKeyType={'done'}
                                    value={password}
                                    secureTextEntry={true}
                                    onChangeText={(val) => {
                                        setPassword(val);
                                    }}
                                    placeholderTextColor={'#a4a4a4'}
                                />
                            </View>
                        </View>
                        <Pressable
                            style={styles.forget}
                            onPress={() => navigation.navigate('EmailRegister', { type: 'passward' })}>
                            <Text style={styles.forgetText}>{t('LoginByEmail.t9')}</Text>
                        </Pressable>
                        <TouchableOpacity style={[styles.bt, styles.row]} onPress={Login}>
                            <Text style={styles.bt_text}>{t('LoginByEmail.t10')}</Text>
                        </TouchableOpacity>
                        <Pressable
                            style={[styles.bt, styles.row]}
                            onPress={() => navigation.navigate('EmailRegister', { type: 'register' })}>
                            <Text style={styles.registerText}>{t('LoginByEmail.t11')}</Text>
                        </Pressable>
                    </View>
                </ScrollView>
            </ImageBackground>
        </View>
    );
}

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    container: {
        flex: 1,
    },
    bg: {
        flex: 1,
        resizeMode: 'contain',
        paddingHorizontal: px2dp(24),
        position: 'relative',
    },
    contentContainerStyle: {
        flexGrow: 1,
    },
    close: {
        position: 'absolute',
        top: '5%',
    },
    content: {
        flex: 1,
        marginTop: '40%',
    },
    logoImage: {
        width: px2dp(240),
        height: px2dp(200),
        marginBottom: px2dp(80),
    },
    title: {
        color: '#fff',
        fontSize: px2dp(44),
        fontWeight: 'bold',
    },
    tips: {
        color: '#A4A4A4',
        fontSize: scale(28),
        marginTop: px2dp(16),
    },
    inputContent: {
        marginTop: px2dp(48),
    },
    input: {
        borderWidth: 1,
        borderColor: 'rgba(255, 255, 255, 0.12)',
        borderRadius: px2dp(16),
        paddingHorizontal: px2dp(16),
        height: px2dp(100),
        justifyContent: 'center',
        marginTop: px2dp(16),
    },
    inputStyle: {
        color: '#ffff',
        fontSize: scale(28),
    },
    forget: {
        marginTop: px2dp(32),
    },
    forgetText: {
        color: '#1777FF',
        fontSize: scale(26),
    },
    bt: {
        justifyContent: 'center',
        borderWidth: 1,
        borderColor: 'rgba(255, 255, 255, 0.12)',
        height: px2dp(96),
        marginTop: px2dp(64),
        borderRadius: px2dp(16),
    },
    bt_text: {
        color: '#fff',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
    registerText: {
        color: '#A4A4A4',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
});
